package com.dankegongyu.lib.common.rx.model;

import com.dankegongyu.lib.common.rx.RxLifecycleUtil;
import com.trello.rxlifecycle3.LifecycleProvider;
import com.trello.rxlifecycle3.LifecycleTransformer;
import com.trello.rxlifecycle3.RxLifecycle;

import androidx.annotation.CallSuper;
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

/**
 * @author wpq
 * @version 1.0
 */
public abstract class RxModel implements IModel, LifecycleProvider<ModelEvent> {

    private final BehaviorSubject<ModelEvent> lifecycleSubject = BehaviorSubject.create();

    @Override
    @NonNull
    @CheckResult
    public final Observable<ModelEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ModelEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleUtil.bindModel(lifecycleSubject);
    }

    @Override
    @CallSuper
    public void onCreate() {
        lifecycleSubject.onNext(ModelEvent.CREATE);
    }

    @Override
    public void onDestroy() {
        lifecycleSubject.onNext(ModelEvent.DESTROY);
    }
}
